package com.yanqu.client.db;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.servercenter.DbInfo;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DbMgr {
    static String centerConnUrl = "jdbc:mysql://10.1.102.11:3306/db_bussinessroad_servercenter?useUnicode=true&characterEncoding=utf8&useSSL=false|root|yanqufuwuduan|20";

    public static Connection parseDbConfig(String connConfigStr) {
        String[] arr = connConfigStr.split("\\|");
        String url = arr[0];
        String userName = arr[1];
        String password = arr[2];
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.err.println("load jdbc driver fail!!");
            throw new RuntimeException(e);
        }
        try {
            Connection conn = DriverManager.getConnection(url, userName, password);
            conn.setAutoCommit(false);
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static DbInfo parseDbInfo(String str) {
        if (StringUtils.isNullOrEmpty(str)) {
            return null;
        }
        JSONObject jObject = null;
        try {
            jObject = JSONObject.parseObject(str);
            DbInfo info = new DbInfo();
            info.setDbName(jObject.getString("dbname"));
            info.setUserName(jObject.getString("dbuser"));
            info.setIp(jObject.getString("ip"));
            info.setPassword(jObject.getString("dbpassword"));
            info.setPort(jObject.getIntValue("port"));
            info.setConnectionNum(jObject.getIntValue("dbconnection"));
            if (jObject.containsKey("partitionCount")) {
                info.setPartitionCount(jObject.getInteger("partitionCount"));
            }
            if (jObject.containsKey("maxConnectionsPerPartition")) {
                info.setMaxConnectionsPerPartition(jObject.getInteger("maxConnectionsPerPartition"));
            }
            if (jObject.containsKey("minConnectionsPerPartition")) {
                info.setMinConnectionsPerPartition(jObject.getInteger("minConnectionsPerPartition"));
            }
            return info;
        } catch (Exception e) {
            return null;
        }
    }

    public static DbInfo getGameServerDbInfo(int serverId) throws SQLException {
        Connection conn = DbMgr.parseDbConfig(centerConnUrl);
        if (null == conn) {
            System.out.println("链接中心服数据库失败！！");
            return null;
        }
        String selectServerDbInfoSql = String.format("select userDatabase from t_s_db_info where serverId=%d", serverId);
        CallableStatement call = conn.prepareCall(selectServerDbInfoSql);
        ResultSet rs = call.executeQuery();
        DbInfo dbInfo = null;
        if (rs.next()) {
            dbInfo = DbMgr.parseDbInfo(rs.getString("userDataBase"));
        }
        conn.close();
        if (null == dbInfo) {
            System.out.println("中心服数据库取不到游戏服数据库配置！！");
            return null;
        }
        return dbInfo;
    }

    public static List<String> getGameWebIpPort(int serverId) throws SQLException {
        Connection conn = DbMgr.parseDbConfig(centerConnUrl);
        if (null == conn) {
            System.out.println("链接中心服数据库失败！！");
            return null;
        }
        String selectServerDbInfoSql = String.format("select gameServerUrl,webServerUrl from t_s_server_list where serverId=%d", serverId);
        CallableStatement call = conn.prepareCall(selectServerDbInfoSql);
        ResultSet rs = call.executeQuery();
        if (rs.next()) {
            List<String> ipPort = new ArrayList<>();
            ipPort.add(rs.getString("gameServerUrl"));
            String webUrl = rs.getString("webServerUrl");
            int portIdx = webUrl.lastIndexOf(":");
            String port = webUrl.substring(portIdx+1, portIdx + 5);
            ipPort.add(port);
            return ipPort;
        }
        conn.close();
        return null;
    }

    public static List<String> getOpenIdBySql(int titleIdNeed, int takeCount, DbInfo dbInfo) throws SQLException {
        String gameDbUrl = "jdbc:mysql://" + dbInfo.getIp() + ":" + dbInfo.getPort() + "/" + dbInfo.getDbName() + "?useUnicode=true&character_set_server=utf8mb4&useSSL=false";
        Connection conn = DriverManager.getConnection(gameDbUrl, dbInfo.getUserName(), dbInfo.getPassword());
        if (null == conn) {
            System.out.println("链接游戏服数据库失败！！");
            return null;
        }
        String sql = String.format("select openId from t_u_user where titleId >= %d and unionUid ='' order by titleId desc limit %d", titleIdNeed, takeCount);
        CallableStatement call = conn.prepareCall(sql);
        ResultSet rs = call.executeQuery();
        List<String> openIds = new ArrayList<>();
        while (rs.next()) {
            openIds.add(rs.getString("openId"));
        }
        conn.close();
        return openIds;
    }
}
